//
//  UIView+Toast.h
//  KangarooDoctor
//
//  Created by mengze on 2024/11/27.
//

#import <UIKit/UIKit.h>
#import "UIView+Toast.h"


@implementation UIView (Toast)

- (void)showToastWithMessage:(NSString *)message duration:(NSTimeInterval)duration {
    
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIView *toast = [[UIView alloc] initWithFrame:CGRectZero];
    toast.backgroundColor = [UIColor blackColor];
    toast.alpha = 0.6;
    toast.layer.cornerRadius = 5;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.text = message;
    label.textColor = [UIColor whiteColor];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.font = [UIFont systemFontOfSize:14.0];
    label.numberOfLines = 0;
    [label sizeToFit];
    
    
    CGRect toastFrame = CGRectMake((window.bounds.size.width - label.frame.size.width) / 2,
                                   window.bounds.size.height - 100,
                                   label.frame.size.width + 20,
                                   label.frame.size.height + 20);
    
    toast.frame = toastFrame;
    label.frame = CGRectMake(0, 0, toastFrame.size.width, toastFrame.size.height);
    
    [toast addSubview:label];
    [window addSubview:toast];
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        toast.alpha = 1.0;
    } completion:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            toast.alpha = 0.0;
        } completion:^(BOOL finished) {
            [toast removeFromSuperview];
        }];
    });
}

@end

